#coding=utf-8
import os
import cv2
import sys
import numpy as np
from PIL import Image


def getImageandLabels(path):
    facesSamples=[]
    ids=[]
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]

    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
    face_cascade.load('C:\\Users\\asus\\AppData\\Roaming\\Python\\Python37\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml')  # 一定要告诉编译器文件所在的具体位置

    for imagePath in imagePaths:
    # 打开图片
        PIL_img = Image.open(imagePath).convert('L')  # 将图像转换为数组
        img_numpy = np.array(PIL_img, 'uint8')
        faces = face_cascade.detectMultiScale(img_numpy)
        # 获取每张图片的id
        id = int(os.path.split(imagePath)[1].split('.')[0])
        # print(os.path.split(imagePath))
        for x, y, w, h in faces:
            facesSamples.append(img_numpy[ y: y + h, x: x + w])
            ids.append(id)

    return facesSamples,ids

if __name__=="__main__":
    #图片路径
    path='C:\\Users\\asus\\Pictures\\Camera Roll\\faces'
    #获取图像数组和id标签数组
    faces,ids=getImageandLabels(path)   # 获取循环对象
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.train(faces, np.array(ids))
    # 保存文件
    recognizer.write('C:\\Users\\asus\\Pictures\\Camera Roll\\trainer.yml')

